package merchant_user_info

import (
	"errors"
	"go.uber.org/zap"
	"math/big"
	"wwt-gin-api/app/global/request"
	"wwt-gin-api/app/global/variable"
	"wwt-gin-api/app/model/api_model"
)

func CreateMerchantUserInfoCurdFactory() *MerchantUserCurd {
	return &MerchantUserCurd{merchantUserModel: api_model.CreateMerchantUserInfoFactory("")}
}

type MerchantUserCurd struct {
	merchantUserModel *api_model.MerchantUserInfo
}

func (receiver *MerchantUserCurd) GetOne(whereMap map[string]interface{}, column string) *api_model.MerchantUserInfo {
	if len(whereMap) == 0 {
		return nil
	}
	res := api_model.CreateMerchantUserInfoFactory("")
	for k, val := range whereMap {
		res.DB = res.Where(k+"= ? ", val)
	}
	if column != "" {
		res.DB = res.DB.Select(column)
	}
	res.First(res)
	return res
}

// AddMerchantBalanceLog
//@param {*} ctx
//@param {*} m_username 商家用户名
//@param {*} money 增加还是扣除的金额
//@param {*} type 0 收入 1支出
//@param {*} source 变更来源 1 分佣奖励  2 发布任务扣除 3充值 4 提现 5 礼品代发购买 6 补差价 7 照妖镜验号 8扣除本金 9 扣除佣金
//@param {*} order_sn 关联订单id/充值/分佣id
//@param {*} remark 备注
func (receiver *MerchantUserCurd) AddMerchantBalanceLog(userName string, money float64, logInfo *request.LogReq) error {
	info := receiver.GetOne(map[string]interface{}{
		"username": userName,
	}, "")
	if info == nil {
		return errors.New("商家不存在")
	}
	info.Balance, _ = receiver.addBalance(info.Balance, money)
	if info.Balance < 0 {
		return errors.New("用户余额不足扣款")
	}
	logType := int8(1) //支出
	if money > 0 {
		logType = 0 //收入
	}
	mBLogModel := &api_model.MerchantBalanceLog{
		MerchantId:    info.Id,
		LevelId:       info.Level,
		Balance:       info.Balance,
		FreezeBalance: info.FreezeBalance,
		Money:         money,
		Type:          logType,
		Source:        logInfo.Source,
		Remark:        logInfo.Remark,
		OrderSn:       logInfo.OrderSn,
	}
	mBLogDb := api_model.CreateMerchantBalanceLogFactory("").Create(&mBLogModel)
	if mBLogDb.Error != nil {
		variable.ZapLog.Error("AddMerchantBalanceLog失败", zap.Error(mBLogDb.Error))
		return errors.New("商家金额日志处理失败")
	}
	return nil
}

func (receiver *MerchantUserCurd) addBalance(balance float64, money float64) (float64, error) {
	balanceF := new(big.Float).SetFloat64(balance)
	moneyF := new(big.Float).SetFloat64(money)
	newBalance := new(big.Float).Add(balanceF, moneyF)
	newBalanceF, _ := newBalance.Float64()
	return newBalanceF, nil
}
